<template>
  <div class="home">
    <!-- 科技感导航栏 -->
    <nav class="main-nav">
      <div class="nav-container">
        <ul class="nav-menu">
          <li class="nav-item">
            <router-link to="/" class="nav-link">
              <span class="nav-text">首页</span>
            </router-link>
          </li>
          <li class="nav-item active">
            <router-link to="/circle" class="nav-link">
              <span class="nav-text">校园圈子</span>
            </router-link>
          </li>
        </ul>
        
        <!-- 搜索框 -->
        <div class="search-box">
          <input
            v-model="searchKeyword"
            placeholder="搜索校园服务..."
            @keyup.enter="handleSearch"
            class="search-input"
          >
        </div>
      </div>
    </nav>
    
    <div class="content-wrapper">
      <!-- 搜索区域 -->
      <div class="search-section">
        <input
          v-model="searchKeyword"
          placeholder="搜索帖子标题或内容..."
          @keyup.enter="handleSearch"
          class="main-search-input"
        >
      </div>

      <!-- 筛选和分类区域 -->
      <div class="filter-category-section">
        <div class="filter-options">
          <select v-model="sortBy" @change="fetchPosts" class="sort-select">
            <option value="latest">最新发布</option>
            <option value="popular">热门推荐</option>
            <option value="most_commented">最多评论</option>
          </select>
        </div>
        
        <!-- 分类导航 -->
        <div class="category-nav">
          <button @click="switchCategory(null)" :class="{ active: !currentCategory }">
            全部
          </button>
          <button v-for="category in categories" :key="category.id" @click="switchCategory(category.id)" :class="{ active: currentCategory === category.id }">
            {{ category.name }}
          </button>
        </div>
      </div>

      <!-- 帖子列表 -->
      <div class="posts-section">
        <h2>校园圈子</h2>
        
        <div v-if="loading" class="loading-state">
          加载中...
        </div>
        
        <div v-else-if="posts.length === 0" class="empty-state">
          暂无帖子数据
        </div>
        
        <div v-else class="post-list">
          <div v-for="post in posts" :key="post.id" class="post-card">
            <div class="post-header">
              <img :src="getAvatarUrl(post.author.avatar)" alt="用户头像" class="avatar" />
              <div class="user-info">
                <div class="username">{{ post.author.username || '匿名用户' }}</div>
                <div class="post-meta">
                  <span>发布时间: {{ formatDate(post.created_at) }}</span>
                  <span>分类: {{ post.category?.name || '未分类' }}</span>
                </div>
              </div>
            </div>
            <div class="post-content" @click="goToPostDetail(post.id)">
              <h3 class="post-title">{{ post.title }}</h3>
              <p class="post-excerpt">{{ post.content.substring(0, 100) }}...</p>
            </div>
            <div class="post-footer">
              <button class="post-stat like-btn" :class="{ liked: post.is_liked }" @click.stop="toggleLike(post)">
                <span class="like-icon">♥</span>
                <span class="like-count">{{ post.likes || 0 }}</span>
              </button>
              <button class="post-stat comment-btn" @click.stop="goToPostDetail(post.id)">
                <span class="comment-icon">💬</span>
                <span class="comment-count">{{ post.comments || 0 }}</span>
              </button>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 创建帖子按钮 -->
      <button class="create-post-btn" @click="goToCreatePost()">+</button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { circleApi } from '@/api'
import { formatDate } from '@/utils/date'

const router = useRouter()
const categories = ref([])
const posts = ref([])
const currentCategory = ref(null)
const searchKeyword = ref('')
const sortBy = ref('latest')
const loading = ref(false)

// 获取分类列表
const fetchCategories = async () => {
  try {
    const res = await circleApi.getCategories()
    categories.value = res.data || []
  } catch (error) {
    console.error('获取分类失败:', error)
    categories.value = []
  }
}

// 获取帖子列表
const fetchPosts = async () => {
  try {
    loading.value = true
    const params = {
      category: currentCategory.value || undefined,
      // 注意：后端DRF的SearchFilter默认使用'search'作为参数名
      search: searchKeyword.value || undefined,
      sort_by: sortBy.value
    }
    // 过滤掉undefined的参数
    const filteredParams = Object.fromEntries(
      Object.entries(params).filter(([_, v]) => v !== undefined)
    )
    const res = await circleApi.getPosts(filteredParams)
    posts.value = res.data?.list || res.results || res.data?.results || []
    
    // 确保每个post都有is_liked属性，并且将like_count映射到likes字段，comment_count映射到comments字段
    // 重点：将后端返回的扁平化author_avatar转换为前端使用的嵌套结构post.author.avatar
    posts.value = posts.value.map(post => ({      
      ...post,      
      is_liked: post.is_liked !== undefined ? post.is_liked : false,      
      // 将后端返回的like_count映射到前端使用的likes字段      
      likes: post.like_count !== undefined ? post.like_count : (post.likes || 0),      
      // 将后端返回的comment_count映射到前端使用的comments字段      
      comments: post.comment_count !== undefined ? post.comment_count : (post.comments || 0),      
      // 构建或完善author对象，确保author.avatar可用      
      author: {        
        ...(post.author || {}),        
        avatar: post.author_avatar || (post.author?.avatar || null),        
        username: post.author_nickname || (post.author?.username || '匿名用户')        
      }      
    }))
  } catch (error) {
    console.error('获取帖子失败:', error)
    posts.value = []
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  fetchPosts()
}

// 切换分类
const switchCategory = (categoryId) => {
  currentCategory.value = categoryId
  fetchPosts()
}

// 跳转到帖子详情
const goToPostDetail = (postId) => {
  router.push({ name: 'postDetail', params: { id: postId } })
}

// 跳转到创建帖子页面
const goToCreatePost = () => {
  router.push({ name: 'createPost' })
}

// 获取用户头像URL
const getAvatarUrl = (avatar) => {
  if (!avatar) {
    return '/default-avatar.png'
  }
  // 检查URL格式，如果不是完整URL则确保以/开头
  if (typeof avatar === 'string') {
    if (!avatar.startsWith('http') && !avatar.startsWith('/')) {
      // 添加媒体文件前缀，适配后端返回的相对路径
      return '/media/avatars/' + avatar
    }
  }
  return avatar
}

// 切换点赞状态
const toggleLike = async (post) => {
  try {
    if (post.is_liked) {
      // 取消点赞
      await circleApi.unlikePost(post.id)
      post.likes = Math.max(0, (post.likes || 0) - 1)
    } else {
      // 添加点赞
      await circleApi.likePost(post.id)
      post.likes = (post.likes || 0) + 1
    }
    // 更新点赞状态
    post.is_liked = !post.is_liked
  } catch (error) {
    console.error('点赞操作失败:', error)
  }
}



// 页面加载时执行
onMounted(() => {
  fetchCategories()
  fetchPosts()
})
</script>

<style scoped>
/* 基础样式 */
.home {
  min-height: 100vh;
  background: linear-gradient(135deg, #0a1128 0%, #121e40 100%);
  color: #b0c4de;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
}

/* 科技感导航栏 */
.main-nav {
  background: linear-gradient(135deg, #000c40 0%, #203a43 100%);
  padding: 0;
  position: sticky;
  top: 0;
  z-index: 1000;
  box-shadow: 0 4px 20px rgba(0, 191, 255, 0.3);
  border-bottom: 1px solid rgba(0, 191, 255, 0.3);
}

.nav-container {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 20px;
  height: 60px;
}

.nav-menu {
  display: flex;
  list-style: none;
  margin: 0;
  padding: 0;
}

.nav-item {
  margin: 0;
  position: relative;
}

.nav-link {
  display: flex;
  align-items: center;
  padding: 0 20px;
  height: 60px;
  color: #b0c4de;
  text-decoration: none;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.nav-link:hover {
  color: #00bfff;
  background: rgba(0, 191, 255, 0.05);
}

.nav-item.active .nav-link {
  color: #00bfff;
  background: rgba(0, 191, 255, 0.1);
  box-shadow: inset 0 0 20px rgba(0, 191, 255, 0.2);
}

.nav-item.active .nav-link::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 3px;
  background: linear-gradient(90deg, transparent, #00bfff, transparent);
}

/* 搜索框 */
.search-box {
  position: relative;
  margin-left: auto;
  margin-right: 20px;
  width: 200px;
}

.search-input {
  width: 100%;
  padding: 6px 15px;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(0, 191, 255, 0.3);
  border-radius: 20px;
  color: #b0c4de;
  font-size: 14px;
  outline: none;
  transition: all 0.3s ease;
}

.search-input:focus {
  border-color: #00bfff;
  box-shadow: 0 0 0 2px rgba(0, 191, 255, 0.2);
}

.search-input::placeholder {
  color: #87ceeb;
}

/* 主要内容区 */
.content-wrapper {
  max-width: 1200px;
  margin: 30px auto;
  padding: 0 20px;
}

/* 主搜索区域 */
.search-section {
  margin-bottom: 30px;
}

.main-search-input {
  width: 100%;
  padding: 15px 25px;
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(0, 191, 255, 0.3);
  border-radius: 25px;
  color: #b0c4de;
  font-size: 16px;
  outline: none;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(0, 191, 255, 0.1);
}

.main-search-input:focus {
  border-color: #00bfff;
  box-shadow: 0 0 0 3px rgba(0, 191, 255, 0.2);
}

.main-search-input::placeholder {
  color: #87ceeb;
}

/* 筛选和分类区域 */
.filter-category-section {
  margin-bottom: 30px;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  align-items: center;
  gap: 20px;
}

.filter-options {
  display: flex;
  gap: 10px;
}

.sort-select {
  padding: 10px 16px;
  border: 1px solid rgba(0, 191, 255, 0.3);
  border-radius: 4px;
  font-size: 16px;
  background: rgba(255, 255, 255, 0.05);
  color: #b0c4de;
  cursor: pointer;
  outline: none;
  transition: all 0.3s ease;
}

.sort-select:hover {
  border-color: #00bfff;
  box-shadow: 0 0 0 2px rgba(0, 191, 255, 0.2);
}

.category-nav {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.category-nav button {
  padding: 8px 16px;
  background-color: rgba(0, 191, 255, 0.05);
  border: 1px solid rgba(0, 191, 255, 0.2);
  border-radius: 4px;
  cursor: pointer;
  color: #b0c4de;
  transition: all 0.3s ease;
  outline: none;
}

.category-nav button.active {
  background-color: #00bfff;
  color: #0a1128;
  border-color: #00bfff;
}

.category-nav button:hover:not(.active) {
  background-color: rgba(0, 191, 255, 0.1);
  border-color: #00bfff;
}

/* 帖子区域 */
.posts-section {
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(0, 191, 255, 0.2);
  border-radius: 12px;
  padding: 25px;
  box-shadow: 0 4px 12px rgba(0, 191, 255, 0.1);
}

.posts-section h2 {
  color: #00bfff;
  text-shadow: 0 0 10px rgba(0, 191, 255, 0.3);
  margin-top: 0;
  margin-bottom: 30px;
  font-size: 24px;
  font-weight: 600;
}

/* 加载状态和空状态 */
.loading-state,
.empty-state {
  text-align: center;
  padding: 50px;
  color: #87ceeb;
}

/* 帖子列表 */
.post-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

/* 帖子卡片 */
.post-card {
  border: 1px solid rgba(0, 191, 255, 0.2);
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;
  background: rgba(255, 255, 255, 0.02);
}

.post-card:hover {
  box-shadow: 0 6px 16px rgba(0, 191, 255, 0.2);
  transform: translateY(-2px);
  border-color: #00bfff;
  background: rgba(255, 255, 255, 0.05);
}

.post-header {
  display: flex;
  align-items: center;
  padding: 15px 20px;
  background: rgba(0, 191, 255, 0.05);
  border-bottom: 1px solid rgba(0, 191, 255, 0.1);
}

.avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  margin-right: 15px;
  border: 3px solid rgba(255, 255, 255, 0.8);
  box-shadow: 0 2px 8px rgba(0, 191, 255, 0.3);
  object-fit: cover;
  transition: all 0.3s ease;
}

.post-card:hover .avatar {
  transform: scale(1.05);
  box-shadow: 0 4px 12px rgba(0, 191, 255, 0.5);
}

.user-info .username {
  font-weight: 600;
  color: #b0c4de;
  margin: 0 0 5px 0;
  text-shadow: 0 0 4px rgba(0, 191, 255, 0.2);
}

.post-meta {
  font-size: 12px;
  color: #87ceeb;
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.post-meta span {
  display: block;
}

.post-content {
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.post-content:hover {
  background: rgba(0, 191, 255, 0.03);
}

.post-title {
  margin: 0 0 15px 0;
  font-size: 18px;
  font-weight: 600;
  color: #00bfff;
  line-height: 1.4;
  text-shadow: 0 0 8px rgba(0, 191, 255, 0.2);
  transition: all 0.3s ease;
}

.post-content:hover .post-title {
  text-shadow: 0 0 12px rgba(0, 191, 255, 0.4);
}

.post-excerpt {
  color: #b0c4de;
  line-height: 1.8;
  font-size: 15px;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.post-footer {
  display: flex;
  justify-content: space-between;
  padding: 15px 20px;
  background: rgba(0, 191, 255, 0.05);
  border-top: 1px solid rgba(0, 191, 255, 0.1);
}

.post-stat {
  color: #87ceeb;
  font-size: 14px;
  display: flex;
  align-items: center;
  transition: all 0.3s ease;
  background: transparent;
  border: none;
  cursor: pointer;
  padding: 8px 16px;
  border-radius: 20px;
  outline: none;
}

/* 点赞按钮样式 */
.like-btn {
  position: static;
  overflow: visible;
}

.like-btn:hover {
  background: transparent;
  color: #87ceeb;
  transform: none;
  box-shadow: none;
}

.like-btn.liked {
  color: #ff69b4;
  background: transparent;
}

/* 评论按钮样式 */
.comment-btn:hover {
  background: rgba(0, 191, 255, 0.1);
  color: #00bfff;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 191, 255, 0.2);
}

/* 图标和计数样式 */
.like-icon,
.comment-icon {
  margin-right: 6px;
  font-size: 16px;
  transition: all 0.3s ease;
}

.like-count,
.comment-count {
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.like-btn.liked .like-count {
  font-weight: 600;
}

/* 按钮点击效果 */
.post-stat:active {
  transform: scale(0.95);
}

/* 创建帖子按钮 */
.create-post-btn {
  position: fixed;
  bottom: 30px;
  right: 30px;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background: linear-gradient(135deg, #00bfff 0%, #0088cc 100%);
  color: white;
  border: none;
  font-size: 28px;
  cursor: pointer;
  box-shadow: 0 4px 20px rgba(0, 191, 255, 0.4);
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  z-index: 999;
  outline: none;
}

.create-post-btn:hover {
  transform: scale(1.1);
  box-shadow: 0 6px 25px rgba(0, 191, 255, 0.6);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .nav-container {
    padding: 0 15px;
  }
  
  .search-box {
    width: 150px;
    margin-right: 10px;
  }
  
  .content-wrapper {
    margin: 15px auto;
    padding: 0 15px;
  }
  
  .filter-category-section {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-options {
    justify-content: center;
  }
  
  .category-nav {
    justify-content: center;
  }
  
  .post-list {
    grid-template-columns: 1fr;
  }
  
  .create-post-btn {
    width: 50px;
    height: 50px;
    bottom: 20px;
    right: 20px;
  }
}
</style>